from io import BytesIO
from random import sample

import xlwt
from django.contrib.admin.utils import quote
from django.http import HttpResponse, JsonResponse, HttpRequest
from django.shortcuts import render, redirect
from django.views.decorators.cache import cache_page

from first.modelmapper import SubjectMapper
from first.models import TbSubject, TbTeacher, User
from first.utils import gen_random_code, Captcha, gen_md5_digest


# Create your views here.
def show_index(request):
    return HttpResponse('<h1>Hello, Django!</h1>')


def show_index2(request):
    fruits = ["苹果", "香蕉", "西瓜"]
    selected_fruits = sample(fruits, 2)
    return render(request, 'index.html', {'fruits': selected_fruits})


def teacher_view(request):
    return render(request, 'table.html')


def show_subjects11(request):
    subject = TbSubject.objects.all().order_by('no')
    return render(request, 'subject.html', {'subjects': subject})


def show_teachers(request):
    sno = request.GET.get("sno")
    teacher = []
    if sno:
        print("sno", sno)
        subject = TbSubject.objects.only('name').get(no=sno)
        print("subject", subject)
        teachers = TbTeacher.objects.filter(sno=subject.no).order_by('no')

        return render(request, 'teachers.html', {
            'subject': subject,
            'teachers': teachers
        })


def praise_or_criticize(request):
    if request.session.get('userid'):
        try:
            tno = int(request.GET.get('tno'))
            teacher = TbTeacher.objects.get(no=tno)
            if request.path.startswith('/praise'):
                teacher.gcount += 1
                count = teacher.gcount
            else:
                teacher.bcount += 1
                count = teacher.bcount
            teacher.save()
            data = {'code': 20000, 'mesg': '操作成功', 'count': count}
        except (ValueError, TbTeacher.DoesNotExist):
            data = {'code': 20001, 'mesg': '操作失败'}
    else:
        data = {'code': 20002, 'mesg': '请先登录'}
    return JsonResponse(data)


def login(request: HttpRequest) -> HttpResponse:
    hint = ''
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username and password:
            password = gen_md5_digest(password)
            print("==========", password)
            user = User.objects.filter(username=username, password=password).first()
            if user:
                request.session['userid'] = user.no
                request.session['username'] = user.username
                return redirect('/')
            else:
                hint = '用户名或密码错误'
        else:
            hint = '请输入有效的用户名和密码'
    return render(request, 'login.html', {'hint': hint})


def get_captcha(request: HttpRequest) -> HttpResponse:
    """验证码"""
    captcha_text = gen_random_code()
    request.session['captcha'] = captcha_text
    image_data = Captcha.instance().generate(captcha_text)
    return HttpResponse(image_data, content_type='image/png')


def logout(request):
    """注销"""
    request.session.flush()
    return redirect('/')

def export_teachers_excel(request):
    # 创建工作簿
    wb = xlwt.Workbook()
    # 添加工作表
    sheet = wb.add_sheet('老师信息表')
    # 查询所有老师的信息
    queryset = TbTeacher.objects.all()
    # 向Excel表单中写入表头
    colnames = ('姓名', '介绍', '好评数', '差评数', '学科')
    for index, name in enumerate(colnames):
        sheet.write(0, index, name)
    # 向单元格中写入老师的数据
    props = ('name', 'detail', 'good_count', 'bad_count', 'subject')
    for row, teacher in enumerate(queryset):
        for col, prop in enumerate(props):
            value = getattr(teacher, prop, '')
            if isinstance(value, TbSubject):
                value = value.name
            sheet.write(row + 1, col, value)
    # 保存Excel
    buffer = BytesIO()
    wb.save(buffer)
    # 将二进制数据写入响应的消息体中并设置MIME类型
    resp = HttpResponse(buffer.getvalue(), content_type='application/vnd.ms-excel')
    # 中文文件名需要处理成百分号编码
    filename = quote('老师.xls')
    # 通过响应头告知浏览器下载该文件以及对应的文件名
    resp['content-disposition'] = f'attachment; filename*=utf-8\'\'{filename}'
    return resp

def get_teachers_data(request):
    queryset = TbTeacher.objects.all()
    names = [teacher.name for teacher in queryset]
    good_counts = [teacher.good_count for teacher in queryset]
    bad_counts = [teacher.bad_count for teacher in queryset]
    return JsonResponse({'names': names, 'good': good_counts, 'bad': bad_counts})


@cache_page(timeout=86400, cache='default')
def show_subjects(request):
    queryset = TbSubject.objects.all()
    subjects = []
    for subject in queryset:
        subjects.append({
            'no': subject.no,
            'name': subject.name,
            'intro': subject.intro,
            'isHot': subject.is_hot
        })
    return JsonResponse(subjects, safe=False)

def show_subjects1(request):
    queryset = TbSubject.objects.all()
    subjects = []
    for subject in queryset:
        subjects.append(SubjectMapper(subject).as_dict())
    return JsonResponse(subjects, safe=False)